from google.appengine.dist import use_library
use_library('django', '1.2')

import cgi
import datetime
from django.utils import simplejson as json
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import common
from model import *
import form
import logging
from utils import str_is_not_blank
import planning
import review
from story import *

class MainHandler(common.BaseRequestHandler):
    def _get(self):
        iterations = []
        id_it = self.request.get('id_it')
        if str_is_not_blank(id_it):
            iterations.append(Iteration.get_by_id(long(id_it)))
        else:
            projects = Project.get_projects()
            for project in projects:
                iterations = iterations + list(project.get_active_iterations())

        self.write_out('index.html', {
                      'iterations': iterations,
                      'story_form':form.StoryForm()
                      })



class ProjectHandler(common.BaseRequestHandler):
    def _get(self):
        projects = Project.all().run()
        self.write_out('projects.html', {
                      'projects': projects
                      })

class IterationHandler(common.BaseRequestHandler):
    def _get(self):
        project_id = self.request.get('project_id')
        project = Project.get_by_id(int(project_id))
        if project.is_user_valid():
            self.write_out('iterations.html', {
                          'project': project
                          })
        else:
            self.not_allowed_error()

class IterationForm(common.BaseRequestHandler):
    def _get(self):
        id = self.request.get('id')
        project_id = ''
        project = None
        iteration_form = None
        if str_is_not_blank(id):
            iteration = Iteration.get_by_id(int(id))
            project_id = iteration.project.key().id()
            project = iteration.get_project()
            iteration_form = form.IterationForm(instance=iteration)
        else:
            project_id = self.request.get('project_id')
            project = Project.get_by_id(int(project_id))
            project_id = project.key().id()
            iteration_form = form.IterationForm()

        if project.is_user_valid():
            self.write_out('iterationForm.html', {
                          'project': project,
                          'iteration_id': id,
                          'form': iteration_form
                          })
        else:
            self.not_allowed_error()

    def post(self):
        id = self.request.get('id')
        data = None
        if str_is_not_blank(id):
            iteration = Iteration.get_by_id(int(id))
            data = form.IterationForm(data=self.request.POST, instance=iteration)
        else:
            data = form.IterationForm(data=self.request.POST)

        project_id = self.request.get('project_id')
        if data.is_valid():
            iteration = data.save(commit=False)
            if not str_is_not_blank(id):
                project = Project.get_by_id(int(project_id))
                iteration.project = project
                iteration.opened_by = users.get_current_user()
                iteration.put()
                iteration.date = datetime.datetime.now()
            
            iteration.put()
            redirect = "/?id_it=" + str(iteration.key().id())
            self.redirect(redirect)
        else:
            project = Project.get_by_id(int(project_id))
            self.write_out('iterationForm.html', {
                          'project': project,
                          'iteration_id': id,
                          'form': data
                          })

class ProjectBacklogHandler(common.BaseRequestHandler):
    def _get(self):
        id = self.request.get('id')
        project_backlog = ProjectBacklog.get_by_id(int(id))
        if project_backlog.get_project().is_user_valid():
            self.write_out('project_backlog.html', {
                          'project_backlog': project_backlog
                          })
        else:
            self.not_allowed_error()

class StoryForm(common.BaseRequestHandler):
    def _get(self):
        id = self.request.get('id')
        iteration_id = ''
        storyForm = None
        iteration = None
        if str_is_not_blank(id):
            story = Story.get_by_id(int(id))
            iteration = story.story_container
            storyForm = form.StoryForm(instance=story)
        else:
            storyForm = form.StoryForm()
            iteration_id = self.request.get('iteration_id')
            iteration = Iteration.get_by_id(int(iteration_id))
            
        if iteration.get_project().is_user_valid():
            self.write_out('storyForm.html', {
                          'iteration': iteration,
                          'story_id': id,
                          'form': storyForm
                          })
        else:
            self.not_allowed_error()

    def post(self):
        id = self.request.get('id')
        data = None
        iteration = None
        iteration_id = ''
        logging.info('id.................'+id)
        if str_is_not_blank(id):
            story = Story.get_by_id(int(id))
            iteration = story.story_container
            data = form.StoryForm(data=self.request.POST, instance=story)
        else:
            data = form.StoryForm(data=self.request.POST)
            iteration_id = self.request.get('iteration_id')
            iteration = Iteration.get_by_id(int(iteration_id))

        if data.is_valid():
            story = data.save(commit=False)
            if not str_is_not_blank(id):
                iteration = Iteration.get_by_id(int(iteration_id))
                story.story_container = iteration
                story.opened_by = users.get_current_user()
            member_id = self.request.get('assigned_to')
            member = Member.get_by_id(int(member_id))
            story.assigned_to = member.user
            story.put()
            redirect = "/story?id=" + str(story.key().id())
            self.redirect(redirect)
        else:
            members = ProjectMember().all().filter('project = ', iteration.project).fetch(10)
            self.write_out('storyForm.html', {
                          'members': members,
                          'iteration': iteration,
                          'story_id': id,
                          'form': data
                          })

class SignupForm(common.BaseRequestHandler):
    def _get(self):
        projects = Project.all().run()
        self.write_out('signupForm.html', {'projects': projects})

    def post(self):
        id_project = self.request.get('id_project')
        project = Project.get_by_id(long(id_project))
        member = Member.get_current_member()
        if not member:
            member = Member(user=users.get_current_user())
            member.put()
        query = ProjectMember.all()
        query.filter('project =', project)
        query.filter('member =', member)
        pm = query.get()
        if not pm:
            pm = ProjectMember(member=member, project=project)
            pm.put()

        self.json_response({ 'id_project': id_project, 'status':pm.status })

class SignupMessageHandler(common.BaseRequestHandler):
    def _get(self):
        self.write_out('sent_signup_request.html', {})

class EvaluationForm(common.BaseRequestHandler):
    def _get(self):
        story_id = self.request.get('id')
        story = Story.get_by_id(int(story_id))
        if story.story_container.get_project().is_user_valid():
            status = ['Implemented', 'Fixed', 'No Reproducible', 'Duplicated', 'Postponed']
            self.write_out('story.html', {
                          'story': story,
                          'status': status
                          })
        else:
            self.not_allowed_error()


class SupportHistoryForm(webapp.RequestHandler):
    def post(self):
        story_id = self.request.get('id')
        story = Story.get_by_id(int(story_id))
        histories = []
        for justification in story.justifications:
            histories.append({'user':justification.author.nickname(), 'text':justification.text})
            
        response = {'history': histories}
        jsonr = json.dumps(response)
        self.response.headers.add_header('content-type', 'application/json', charset='utf-8')
        self.response.out.write(jsonr)

class ChangeIterationStatus(webapp.RequestHandler):
    def post(self):
        iteration_id = self.request.get('iteration_id')
        iteration = Iteration.get_by_id(int(iteration_id))
        status = self.request.get('status')
        iteration.status = status
        iteration.put()
        response = {'status':iteration.status}
        jsonr = json.dumps(response)
        self.response.headers.add_header('content-type', 'application/json', charset='utf-8')
        self.response.out.write(jsonr)

application = webapp.WSGIApplication(
                                     [('/', MainHandler),
                                     ('/iterations', IterationHandler),
                                     ('/projects', ProjectHandler),
                                     ('/iteration_form', IterationForm),
                                     ('/story_form', StoryForm),
                                     ('/signup', SignupForm),
                                     ('/sent_signup_request', SignupMessageHandler),
                                     ('/assign_form', AssignForm),
                                     ('/add_time_worked', TimeWorkedForm),
                                     ('/edit_description', EditStoryDescription),
                                     ('/change_story_status', ChangeStoryStatus),
                                     ('/reopen_story', ReopenStory),
                                     ('/comment_story', CommentStory),
                                     ('/project_backlog', ProjectBacklogHandler),
                                     ('/postpone_story', PostponeStoryHandler),
                                     ('/stories_backlog', review.StoryBackLogHandler),
                                     ('/comment_review_story', review.CommentHandler),
                                     ('/edit_support_comment', review.StoryObservationHandler),
                                     ('/move_stories', review.CopyStories),
                                     ('/review_chat', review.ChatHandler),
                                     ('/get_support_history', SupportHistoryForm),
                                     ('/iteration_planning', planning.IterationPlanningHandler),
                                     ('/edit_ip_description', planning.EditIPStoryDescriptionHandler),
                                     ('/planning_assign_form', planning.AssignDeveloperHandler),
                                     ('/planning_time_form', planning.EditTimeHandler),
                                     ('/planning_priority_form', planning.PriorityHandler),
                                     ('/planning_category_form', planning.CategoryHandler),
                                     ('/planning_name_form', planning.NameHandler),
                                     ('/create_story', planning.CreateStory),
                                     ('/move_story', planning.PostponeStoryHandler),
                                     ('/comment_planning_story', planning.CommentStoryHandler),
                                     ('/planning_chat', planning.ChatHandler),
                                     ('/change_iteration_status', ChangeIterationStatus),
                                     ('/story', EvaluationForm)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
